package com.mrzhou.study.controller;

import com.mrzhou.core.tool.utils.StringUtil;
import com.mrzhou.study.entity.TempEntity;
import com.mrzhou.study.service.ITempService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api("测试")
@Slf4j
public class TestController {

    @Autowired
    private ITempService tempService;

    @GetMapping("transmit")
    @ApiOperation("通过后台控制浏览器跳转到指定路由主机")
    public void transmit(@ApiParam(value = "跳转链接", required = true) @RequestParam("redirectUrl") String redirectUrl,
                         HttpServletResponse response) {
        response.setStatus(HttpStatus.FOUND.value()); // 设置302
        response.setHeader("location", redirectUrl); // 在响应头中设置location, 让浏览器调转到指定链接中
    }

    /**
     * 处理消逝的光芒蓝图文件
     * 获取全部蓝图
     */
    @GetMapping("parse")
    @ApiOperation("处理消逝的光芒蓝图文件")
    public void parse() throws Exception {
       this.handlerDyingLightFile("F:/MrZhou/临时文件/消逝的光芒/data/inventory", "C:/Users/qiang.zhou/Desktop/inventory.txt");
        this.handlerDyingLightFile("F:/MrZhou/临时文件/消逝的光芒/data/collectables", "C:/Users/qiang.zhou/Desktop/蓝图.txt");
    }

    /**
     * 解析文件信息
     * @param path 所在文件夹的绝对路径
     * @param outFileName 输出的文件名称
     */
    private void handlerDyingLightFile(String path, String outFileName) throws Exception {
        Properties prop = new Properties();
        prop.load(new BufferedReader(new FileReader("F:/MrZhou/临时文件/消逝的光芒/data/text/common_texts_all.bin.txt")));

        BufferedWriter writer = new BufferedWriter(new FileWriter(outFileName, true));
        // 1. 载入文件， 逐个文件解析
        File collectablesFile = new File(path);
        List<TempEntity> list = new ArrayList<>();
        Map<String, Map<String, String>> map = new HashMap<>(32);
        Arrays.stream(collectablesFile.listFiles()).forEach(file -> {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                Map<String, String> collectables = new HashMap<>(16);
                String code ="", quality = "", type = "", name = "";

                // 解析文件流
                String t = reader.readLine();
                writer.write("\t//"+ file.getName() + "\n");
                while (null != t) {
                    if (t.contains("Item(")) {
                        code = t.substring(t.indexOf("\"") + 1, t.lastIndexOf("\""));
                        while (!t.contains("}")) {
                            if (t.contains("Color(")) {
                                quality = t.substring(t.indexOf("(") + 1, t.indexOf(")"));
                            }
                            if (t.contains("ItemType(")) {
                                type = t.substring(t.indexOf("(") + 1, t.indexOf(")"));
                            }
                            if (t.contains("Name(\"&")) {
                                name = t.substring(t.indexOf("\"") + 2,  t.lastIndexOf("\"") - 1);
                            }
                            t = reader.readLine();
                        }
                        collectables.put(code, quality);
                        if (code.contains("Craftplan_")) {
                            TempEntity entity = new TempEntity();
                            entity.setGoodsFile(file.getName());
                            entity.setGoodsCode(code);
                            entity.setGoodsName(this.getGoodsName(prop, code, name));
                            entity.setQuality(quality);
                            entity.setType(type);
                            list.add(entity);
                            writer.write("\tItem(\"" + code + "\");\t//" + quality + "\n");
                        } else if (!file.getName().contains("collectables") && StringUtil.isNotBlank(code) && StringUtil.isNotBlank(quality)) {
                            TempEntity entity = new TempEntity();
                            entity.setGoodsFile(file.getName());
                            entity.setGoodsCode(code);
                            entity.setGoodsName(this.getGoodsName(prop, code, name));
                            entity.setQuality(quality);
                            entity.setType(type);
                            list.add(entity);
                            writer.write("\tItem(\"" + code + "\");\t//" + quality + "\n");
                        }

                        continue;
                    }
                    t = reader.readLine();
                }
                map.put(file.getName(), collectables);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        writer.flush();
        writer.close();
        tempService.saveBatch(list.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TempEntity::getGoodsCode))), ArrayList::new)));
    }

    private String getGoodsName(Properties prop, String code, String name) {
        // 尝试直接使用code获取名称
        if (StringUtil.isNotBlank(prop.getProperty(code))) {
            return prop.getProperty(code);
        }
        if (StringUtil.isNotBlank(prop.getProperty(code + "_n"))) {
            return prop.getProperty(code + "_n");
        }
        if (StringUtil.isNotBlank(prop.getProperty(code + "_N"))) {
            return prop.getProperty(code + "_N");
        }
        if (StringUtil.isNotBlank(name)) {
            return prop.getProperty(name);
        }
        return null;
    }

    public static void main(String[] args) {
        getStr("具体用法 （要element使用带有一些（可选）选项的 html2canvas 呈现，只需调用html2canvas(element, options);）", 33);
    }

    public static void getStr(String str, int maxPx) {
        Font f = new Font("Arial", Font.PLAIN, 12);
        JComponent j = new JLabel();
        FontMetrics fm = j.getFontMetrics(f);
        System.out.println("字符总长total: " + fm.stringWidth(str));

        char[] chars = str.toCharArray();
        // 保存每行需要的长度
        List<String> list = new ArrayList<>();
        // 循环计算每个字符的长度
        int totalPx = 0;
        // 用以保存每行的字符
        String t = "";
        for (char c: chars) {
            totalPx += fm.stringWidth(c+"");
            if (totalPx <= maxPx) {
                t = t + c;
            } else {
                list.add(t);
                // 重置变量
                t = c + "";
                totalPx = 0;
            }
        }
        list.add(t);
        System.out.println(list);
    }





}
